package com.example.yyy

import android.app.Application
import android.content.Context
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class MainApplication :Application(){

     var allString:String by NotNullSingleValueVar()

//    fun getallString():String{
//        return allString
//    }
//
//    fun setallString(allString:String){
//       this.allString = allString
//    }
    override fun onCreate() {
        super.onCreate()
        instance = this
    }


    //定义一个属性管理类，进行非空和重复赋值的判断
    private class NotNullSingleValueVar<T>() : ReadWriteProperty<Any?, T> {
        private var value: T? = null
        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return value?: throw IllegalStateException("application not initialized")
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            this.value = if (this.value == null) value
            else throw IllegalStateException("application already initialized")
        }
    }

    companion object{
        //声明可空都属性
//        private var instance:MainApplication? = null

        //声明延迟属性
//        private lateinit var instance:MainApplication

        //利用系统自带的Delegates生成委托属性
//        private var instance:MainApplication by Delegates.notNull()

        private var instance:MainApplication by NotNullSingleValueVar()
        fun instance() = instance
    }
}

